<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Manage extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    public $table = 'manage';

    public static $manage_name = 'username'; //全局显示的管理员名使用真名


    /**
     * 管理管理员角色
     *
     * @return void
     */
    public function conRole()
    {
        return $this->belongsToMany('App\Models\Role', 'manage_role', 'manage_id', 'role_id');
    }

    /**
     * 新书书籍收藏关联
     */
    public function conShop()
    {
        return $this->belongsToMany('App\Models\Shop', 'book_home_manage_shop', 'manage_id', 'shop_id')
            ->select('id', 'shop_name', 'shop_id');
    }


    /**
     * 根据管理员id，判断密码是否正确
     * @param manage_id
     * @param password
     */
    public static function passwordIsSuccess($manage_id, $password)
    {
        $old_password = self::where('id', $manage_id)->where('is_del', 1)->value('password');
        if (empty($old_password)) {
            return false;
        }
        if ($old_password != md5($password)) {
            return false;
        }
        return true;
    }

    /**
     * 根据管理员id  获取管理员名称
     * @param manage_id 管理员id
     */
    public static function getManageNameByManageId($manage_id)
    {
        return self::where('id', $manage_id)->value(self::$manage_name);
    }
    /**
     * 根据管理员id，查询所有下属管理员id
     * @param manage_id
     */
    public function getManageIdAll($manage_id)
    {
        if ($manage_id == 1) {
            return $this->where('is_del', 1)->pluck('id');
        }
        $data = [];
        $result = $this->where('is_del', 1)->where('manage_id', $manage_id)->pluck('id')->toArray();
        $data = $result; //添加原本账号
        foreach ($result as $key => $val) {
            $data = $this->disManageId($val, $data);
        }
        $data[] = $manage_id; //附带自己
        $data = array_unique($data);
        sort($data);
        return $data;
    }
    /**
     * 处理递归数据
     */
    public function disManageId($manage_id, $data)
    {
        $result = $this->where('is_del', 1)->where('manage_id', $manage_id)->pluck('id');
        foreach ($result as $key => $val) {
            $data[] = $val;
            $data = $this->disManageId($val, $data);
        }
        return $data;
    }


    /**
     * 获取筛选管理员id
     */
    public function getFilterLists($field, $shop_all_id = null, $manage_id_all = null)
    {
        $manage_id = [];
        if ($shop_all_id && config('book_home_type')) {
            // $bookHomeManageShopModel = new BookHomeManageShop();
            // $manage_id = $bookHomeManageShopModel->getMangeIdByShopId($shop_all_id);
        }
        $manage_id[] = request()->manage_id; //添加一个自己

        $self_manage_id = request()->manage_id;
        $data = $this->select($field)
            ->where('is_del', 1)
            ->where(function ($query) use ($self_manage_id, $shop_all_id, $manage_id) {
                if ($shop_all_id && $self_manage_id != 1) {
                    $query->whereIn('id', $manage_id);
                }
                if ($self_manage_id != 1) {
                    $query->where('id', '<>', 1);
                }
            })
            ->where(function ($query) use ($manage_id_all) {
                if ($manage_id_all) {
                    $query->whereIn('id', $manage_id_all);
                }
            })
            ->get()
            ->toArray();
        return $data;
    }
    /**
     * 管理员列表
     * @param keywords 关键字搜索
     * @param manage_id_all 关键字搜索
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param limit 限制条数  默认 10
     */
    public function lists($keywords, $manage_id, $start_time, $end_time, $limit = 10)
    {
        $res = $this->select(['id', 'account', 'username', 'tel', 'create_time', 'end_login_time', 'end_login_ip','resource_business_ids'])
            ->with(['conRole' => function ($query) {
                $query->select('role.id', 'role_name')->where('role.is_del', 1);
            }])
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('account', 'like', '%' . $keywords . '%')->orWhere('username', 'like', '%' . $keywords . '%');
                }
            })
            ->where(function ($query) use ($start_time, $end_time) {
                if (!empty($start_time) && !empty($end_time)) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })
            ->whereIn('id', $manage_id)
            ->where('id', '<>', 1)
            ->where('is_del', 1)
            ->orderBy('id')
            ->paginate($limit)
            ->toArray();
        return $res;
    }

    /**
     * 管理员详情
     * @param id 管理员id
     */
    public function detail($id, $manage_id)
    {
        $res = $this->select(['id', 'account', 'username', 'tel', 'create_time', 'end_login_time', 'end_login_ip','resource_business_ids'])
            ->with(['conRole' => function ($query) {
                $query->select('role.id', 'role_name')->where('role.is_del', 1);
            }])
            ->whereIn('id', $manage_id)
            ->where('id', '<>', 1)
            ->where('id', $id)
            ->where('is_del', 1)
            ->first();
        return $res;
    }

    /**
     *  管理员添加
     * @param $data 添加的数据
     */
    public function add($data, $field = [])
    {
        $this->account = $data->account;
        $this->username = $data->username;
        $this->password = md5($data->password);
        $this->tel = $data->tel;
        $this->manage_id = $data->manage_id;
        $this->resource_business_ids = $data->resource_business_ids;
        $this->is_del = 1;
        $this->save();

        $manageRoleModelObj = new ManageRole();
        $manageRoleModelObj->manageRoleChange($this->id, $data->role_ids, 'add');

        return  $this->id;
    }

    /**
     * 修改管理员
     * @param $data 添加的数据
     */
    public function change($data, $field = [], $findWhere = [])
    {
        $res = $this->where('is_del', 1)->find($data['id']);
        if (!$res) {
            return false;
        }
        $res->username = $data->username;
        $res->tel = $data->tel;
        $res->resource_business_ids = $data->resource_business_ids;
        $res->save();

        $manageRoleModelObj = new ManageRole();
        $manageRoleModelObj->manageRoleChange($res->id, $data->role_ids, 'change');

        return  $res->id;
    }
    /**
     * 判断是否是超级管理员(拥有绝对的数据管理权限)
     */
    public function isSuperAdmin($id = null)
    {
        if (empty($id)) {
            $id = request()->manage_id;
        }
        if (empty($id)) {
            return false;
        }
        if ($id == 1) {
            return true; //是超级管理员，如果后期要增加管理员，则在数据中加入对应管理员id
        }
        return false;
    }
}
